package com.diamond.web.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.diamond.web.security.RoleSign;
import com.diamond.web.utils.ApplicationInitUtils;

/**
 * 权限拦截器
 * @author Diamond
 * 
 */
public class PermissionInterceptor implements HandlerInterceptor {

	Logger log = Logger.getLogger(getClass());
	
	String notInterceptor;
	
	public PermissionInterceptor(String notInterceptor) {
		this.notInterceptor = notInterceptor;
	}
	
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String path = request.getRequestURI();
//		log.info("handler:"+path);
		path = path.substring(path.indexOf(ApplicationInitUtils.URL_PATTERN)+ApplicationInitUtils.URL_PATTERN.length());
		if(path.contains(";")){  //防止权限绕过
			path = path.substring(0,path.indexOf(";"));
		}
		if(path.contains("_")){	 //子权限连接 识别
			path = path.substring(0,path.indexOf("_"));
		}
		if(path.endsWith("Data")){ //数据权限连接识别
			path = path.substring(0, path.length()-4);
		}
		Subject subject = SecurityUtils.getSubject();
		if(!subject.hasRole(RoleSign.SUPER_ADMIN)){
			if(!path.matches(notInterceptor)){
				log.info("check permission:	"+path);
				subject.checkPermission(path);
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}


}
